from common.views.base_views import BaseAPIView
from apps.product.models import *
from rest_framework.response import Response
from decimal import Decimal as D
from django.views.generic.base import View
from django.shortcuts import render
from apps.message.views import CreateMessageView
from apps.message.models import Message
from django.http import HttpResponseRedirect, HttpResponse
import datetime
from apps.mix import tasks
from django.db import transaction

TEST_STORE = 'STORE1'
TEST_BRAND = 'BRAND1'
TEST_BRAND_NO = 'WR1'
TEST_PRODUCT = 'PRODUCT1'
TEST_PRODUCT_NO = 'DW1'
TEST_PRODUCT_AGE_CODE = '2018C'
TEST_PRODUCT_PRICE = D("0.05")
TEST_PRODUCT_START_PRE_SALE_TIME = datetime.date(2018, 2, 1)
TEST_PRODUCT_END_PRE_SALE_TIME = datetime.date(2018, 2, 10)


class CreateStore(BaseAPIView):
    def post(self, request, *args, **kwargs):
        store = Store()
        store.name = TEST_STORE
        store.store_type = Store.StoreType.BRAND.name
        store.store_desc = '-'
        store.mountain_desc = '-'
        store.mountain_history = '-'
        store.maker_and_tech_desc = '-'
        store.repo_desc = '-'
        store.save()
        return Response(store.as_dict())


class CreateBrand(BaseAPIView):
    def post(self, request, *args, **kwargs):
        brand = Brand()
        brand.store = Store.objects.get(name=TEST_STORE)
        brand.name = TEST_BRAND
        brand.logo_public_file_id = '-'
        brand.attention_account = 0
        brand.video_banner_public_file_id = '-'
        brand.no = TEST_BRAND_NO
        brand.save()
        return Response(brand.as_dict())


class CreateProduct(BaseAPIView):
    """
    brand = models.ForeignKey(Brand, "品牌")
    name = models.CharField("产品名")
    tea_type = models.CharField("产品类型", choices= Product.TeaType.get_choices(), default=Product.TeaType.TT_RAW.name)
    no = models.CharField("编号", default='', blank=True, null=True)
    logo_public_file_id = models.CharField("ProductLogo公开文件ID", max_length=64)
    stock = models.IntegerField("库存")
    age_code = models.CharField("年份码", blank=True, null=True)
    tea_cake_type = models.CharField("茶饼类型", choices=Product.TeaCakeType.get_choices(), default=Product.TeaCakeType.SMALL.name)
    status = models.CharField("状态", choices=Product.ProductStatus.get_choices())
    pre_sale_price = models.DecimalField("预售价格", max_digits=10, decimal_places=2)
    pre_sale_weixin_article_link = models.CharField("预售微信公众号文章链接", blank=True, null=True)
    keeping_count = models.IntegerField("用户持仓量")
    trading_count = models.IntegerField("交易中数量", default=0)
    picked_count = models.IntegerField("已提仓量")
    max_price = models.DecimalField("最高价", max_digits=10, decimal_places=2)
    avg_price = models.DecimalField("历史平均价", max_digits=10, decimal_places=2, blank=True, null=True)
    up_down_percent = models.DecimalField("涨跌幅", max_digits=5, decimal_places=2)
    # intro = models.TextField("简介")
    # maker_and_tech_desc = models.CharField("制茶人和技术介绍（长图）")  # TODO
    # desc = models.CharField("产品介绍（长图）")  # TODO
    # in_repo_certify_data = models.CharField("产品入库公正文书（长图）")  # TODO
    pre_sale_start_time = models.DateTimeField("预售开始时间")
    pre_sale_end_time = models.DateTimeField("预售结束时间", blank=True, null=True)
    is_unfolded = models.BooleanField(verbose_name="是否展开", default=False)
    # BannerVideo
    video_banner_public_file_id = models.CharField("视频Banner公开文件ID", max_length=64, blank=True, null=True)
    # 文本字段
    specification = models.CharField("规格", max_length=256)
    kind = models.CharField("种类", blank=True, null=True)
    material = models.CharField("原料", blank=True, null=True)
    repo_id = models.CharField("仓库ID", max_length=64, blank=True, null=True)
    age = models.CharField("年份", blank=True, null=True)
    publish_count = models.IntegerField("发行量")
    publish_unit = models.CharField("发行单位", blank=True, null=True)
    technology = models.CharField("工艺", blank=True, null=True)
    tea_mountain = models.CharField("茶山", blank=True, null=True)
    altitude = models.IntegerField("海拔（米）", blank=True, null=True)
    ancient_tea_tree_count = models.IntegerField("古树量(棵）", blank=True, null=True)
    year_avg_temperature = models.CharField("年平均气温", blank=True, null=True)
    year_avg_precipitation = models.CharField("年平均降水", blank=True, null=True)
    made_in = models.CharField("产地", blank=True, null=True)
    """
    def post(self, request, *args, **kwargs):
        product = Product()
        product.brand = Brand.objects.get(name=TEST_BRAND)
        product.name = TEST_PRODUCT
        product.tea_type = Product.TeaType.TT_RAW.name
        product.no = TEST_PRODUCT_NO
        product.logo_public_file_id = '-'
        # product.stock = 100 #
        product.age_code = TEST_PRODUCT_AGE_CODE
        product.tea_cake_type = Product.TeaCakeType.SMALL.name
        product.status = Product.ProductStatus.REPO_IN_ING
        product.pre_sale_price = TEST_PRODUCT_PRICE
        product.pre_sale_weixin_article_link = '-'
        # product.keeping_count = 0 #
        # product.trading_count = 0 #
        # product.picked_count = 0 #
        product.max_price = TEST_PRODUCT_PRICE
        product.avg_price = TEST_PRODUCT_PRICE
        product.up_down_percent = D('0.00')
        product.pre_sale_start_time = TEST_PRODUCT_START_PRE_SALE_TIME
        product.pre_sale_end_time = TEST_PRODUCT_END_PRE_SALE_TIME
        product.is_unfolded = True
        product.video_banner_public_file_id = '-'
        product.specification = "357g/饼"
        product.kind = "普洱熟茶"
        product.material = "云南大叶种晒青毛茶"
        product.repo_id = "55b78c67028648e689dc273e928de72c"
        product.age = "2018年春"
        product.publish_count = 3000
        product.publish_unit = "饼"
        product.technology = "石墨"
        product.tea_mountain = "板山"
        product.altitude = 1305
        product.ancient_tea_tree_count = 10
        product.year_avg_precipitation = "1500毫米"
        product.year_avg_temperature = "10-13°C"
        product.made_in = "云南省普洱市"
        product.save()
        return Response(product.as_dict())


class SetAvgPriceView(View):
    def get_base_context(self, product_id):
        product = Product.objects.get(pk=product_id)
        return {
            "product": product,
            "users": User.objects.filter(certificate_state=User.CertificateState.VERIFIED.name).order_by('mobile'),
            "user_infos": '',
            "error_msgs": [],
        }

    def get(self, request, *args, **kwargs):
        from django.contrib.auth.models import User as DjangoUser
        if not (getattr(request, 'user') and isinstance(request.user, DjangoUser)):
            return HttpResponseRedirect('/admin/')

        context = self.get_base_context(product_id=kwargs.get('id'))
        return render(request=request, template_name='product/set-avg-price.html', context=context)

    def post(self, request, *args, **kwargs):
        from django.contrib.auth.models import User as DjangoUser
        if not (getattr(request, 'user') and isinstance(request.user, DjangoUser)):
            return HttpResponseRedirect('/admin/')

        product_id = request.POST.get('product_id')
        context = self.get_base_context(product_id=product_id)
        product = context['product']  # type: Product

        error_msgs = []
        prompt_msgs = []

        avg_price_custom = request.POST.get('avg_price_custom')
        context['avg_price_custom'] = avg_price_custom
        try:
            avg_price_custom = Decimal(str(avg_price_custom))
            prompt_msgs.append('修改成功')
        except:
            error_msgs.append('价格必须为精度为2的两位小数')
            context['error_msgs'] = error_msgs
            return render(request=request, template_name='product/set-avg-price.html', context=context)

        context['prompt_msgs'] = prompt_msgs

        product.avg_price_custom = avg_price_custom
        product.save()
        return render(request=request, template_name='product/set-avg-price.html', context=context)

class DispatchProductView(View):
    def get_base_context(self, product_id):
        product = Product.objects.get(pk=product_id)
        return {
            "product": product,
            "users": User.objects.filter(certificate_state=User.CertificateState.VERIFIED.name).order_by('mobile'),
            "user_infos": '',
            "error_msgs": [],
        }

    def get(self, request, *args, **kwargs):
        id = kwargs.get('id')
        context = self.get_base_context(product_id=id)
        product = context['product']  # type: Product
        if not product.free_repo_cost:
            return HttpResponse('该产品未设置 免存仓费，不能分发')
        return render(request=request, template_name='product/dispatch.html', context=context)

    def post(self, request, *args, **kwargs):
        from tuntun.settings import REGEX_MOBILE
        import re
        import time
        import datetime
        import uuid
        from apps.repo.models import Repo

        product_id = request.POST.get('product_id')
        context = self.get_base_context(product_id=product_id)
        product = context['product']  # type: Product
        user_infos = request.POST.get('user_infos').strip()
        mobile_count_map = {}
        error_msgs = []

        if not product.free_repo_cost:
            return HttpResponse('该产品未设置 免存仓费，不能分发')
        if product.status not in [Product.ProductStatus.REPO_IN_ING.name, Product.ProductStatus.REPO_ENTERED.name]:
            error_msgs.append('可以分发的产品必须是预售之前：当前状态-%s' % getattr(Product.ProductStatus, product.status).value)

        if product.publish_count != product.in_repo_count():
            error_msgs.append('产品为完全入库: 发行量-%d  入库量-%d' % (product.publish_count, product.in_repo_count()))

        gbs = GoodsBlock.objects.filter(product_id=product_id)

        current_offset = 0
        for idx, ui in enumerate(user_infos.splitlines()):
            tmp = ui.strip()
            if not tmp:
                continue
            elif ':' not in tmp:
                error_msgs.append('格式错误：%s' % tmp)

            mobile, count = tmp.split(':')[0], tmp.split(':')[1]
            if not re.match(REGEX_MOBILE, mobile):
                error_msgs.append('手机号格式错误：%s' % tmp)
            if not count.isdigit():
                error_msgs.append('数量不是数字：%s' % tmp)
            count = int(count)

            user = User.objects.filter(mobile=mobile).first()
            if not user:
                error_msgs.append('用户不存在：%s' % tmp)
            if user and user.certificate_state != User.CertificateState.VERIFIED.name:
                error_msgs.append('用户未实名认证：%s' % tmp)

            if mobile in mobile_count_map.keys():
                error_msgs.append('手机号重复：%s' % tmp)

            if count == 0:
                error_msgs.append('数量不能为0：%s' % tmp)

            mobile_count_map[tmp.split(':')[0]] = {
                'count': count,
                'user': user,
                'total_value': Decimal(str(count)) * product.pre_sale_price,
                'gbs': gbs[current_offset:current_offset+count],
                'gbs_count': len(gbs[current_offset:current_offset+count]),
            }
            current_offset += count

        total_count = sum([v['count'] for k, v in mobile_count_map.items()])
        if total_count != product.publish_count:
            error_msgs.append('分发总数必须等于产品发行总数：分发总数-%d  发行总数-%d ' % (total_count, product.publish_count))

        if error_msgs:
            context['error_msgs'] = error_msgs
            context['user_infos'] = user_infos
            return render(request=request, template_name='product/dispatch.html', context=context)

        # 执行
        t = tasks.async_dispatch.delay(product_id, user_infos)
        product.dispatch_task_id = t.id
        product.save()

        return HttpResponseRedirect('/admin/product/product/')